package cn.ld.module.system.controller.admin.auth;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.ld.framework.common.enums.CommonStatusEnum;
import cn.ld.framework.common.enums.UserTypeEnum;
import cn.ld.framework.common.pojo.CommonResult;
import cn.ld.framework.security.config.SecurityProperties;
import cn.ld.framework.security.core.util.SecurityFrameworkUtils;
import cn.ld.module.system.controller.admin.auth.vo.AuthLoginInVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthLoginOutVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthPermissionInfoOutVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthRegisterInVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthResetPasswordInVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthSmsLoginInVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthSmsSendInVO;
import cn.ld.module.system.controller.admin.auth.vo.AuthSocialLoginInVO;
import cn.ld.module.system.convert.auth.AuthConvert;
import cn.ld.module.system.dal.entity.permission.MenuEntity;
import cn.ld.module.system.dal.entity.permission.RoleEntity;
import cn.ld.module.system.dal.entity.user.AdminUserEntity;
import cn.ld.module.system.enums.logger.LoginLogTypeEnum;
import cn.ld.module.system.service.auth.AdminAuthService;
import cn.ld.module.system.service.permission.MenuService;
import cn.ld.module.system.service.permission.PermissionService;
import cn.ld.module.system.service.permission.RoleService;
import cn.ld.module.system.service.social.SocialClientService;
import cn.ld.module.system.service.user.AdminUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import static cn.ld.framework.common.pojo.CommonResult.success;
import static cn.ld.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.ld.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 认证")
@RestController
@RequestMapping("/system/auth")
@Validated
@Slf4j
public class AuthController {

    @Resource
    private AdminAuthService authService;
    @Resource
    private AdminUserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private SocialClientService socialClientService;

    @Resource
    private SecurityProperties securityProperties;

    @PostMapping("/login")
    @PermitAll
    @Operation(summary = "使用账号密码登录")
    public CommonResult<AuthLoginOutVO> login(@RequestBody @Valid AuthLoginInVO inVO) {
        return success(authService.login(inVO));
    }

    @PostMapping("/logout")
    @PermitAll
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            authService.logout(token, LoginLogTypeEnum.LOGOUT_SELF.getType());
        }
        return success(true);
    }

    @PostMapping("/refresh-token")
    @PermitAll
    @Operation(summary = "刷新令牌")
    @Parameter(name = "refreshToken", description = "刷新令牌", required = true)
    public CommonResult<AuthLoginOutVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        return success(authService.refreshToken(refreshToken));
    }

    @GetMapping("/get-permission-info")
    @Operation(summary = "获取登录用户的权限信息")
    public CommonResult<AuthPermissionInfoOutVO> getPermissionInfo() {
        // 1.1 获得用户信息
        AdminUserEntity user = userService.getUser(getLoginUserId());
        if (user == null) {
            return success(null);
        }

        // 1.2 获得角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdListByUserId(getLoginUserId());
        if (CollUtil.isEmpty(roleIds)) {
            return success(AuthConvert.INSTANCE.convert(user, Collections.emptyList(), Collections.emptyList()));
        }
        List<RoleEntity> roles = roleService.getRoleList(roleIds);
        roles.removeIf(role -> !CommonStatusEnum.ENABLE.getStatus().equals(role.getStatus())); // 移除禁用的角色

        // 1.3 获得菜单列表
        Set<Long> menuIds = permissionService.getRoleMenuListByRoleId(convertSet(roles, RoleEntity::getId));
        List<MenuEntity> menuList = menuService.getMenuList(menuIds);
        menuList = menuService.filterDisableMenus(menuList);

        // 2. 拼接结果返回
        return success(AuthConvert.INSTANCE.convert(user, roles, menuList));
    }

    @PostMapping("/register")
    @PermitAll
    @Operation(summary = "注册用户")
    public CommonResult<AuthLoginOutVO> register(@RequestBody @Valid AuthRegisterInVO registerInVO) {
        return success(authService.register(registerInVO));
    }

    // ========== 短信登录相关 ==========

    @PostMapping("/sms-login")
    @PermitAll
    @Operation(summary = "使用短信验证码登录")
    public CommonResult<AuthLoginOutVO> smsLogin(@RequestBody @Valid AuthSmsLoginInVO inVO) {
        return success(authService.smsLogin(inVO));
    }

    @PostMapping("/send-sms-code")
    @PermitAll
    @Operation(summary = "发送手机验证码")
    public CommonResult<Boolean> sendLoginSmsCode(@RequestBody @Valid AuthSmsSendInVO inVO) {
        authService.sendSmsCode(inVO);
        return success(true);
    }

    @PostMapping("/reset-password")
    @PermitAll
    @Operation(summary = "重置密码")
    public CommonResult<Boolean> resetPassword(@RequestBody @Valid AuthResetPasswordInVO inVO) {
        authService.resetPassword(inVO);
        return success(true);
    }

    // ========== 社交登录相关 ==========

    @GetMapping("/social-auth-redirect")
    @PermitAll
    @Operation(summary = "社交授权的跳转")
    @Parameters({
            @Parameter(name = "type", description = "社交类型", required = true),
            @Parameter(name = "redirectUri", description = "回调路径")
    })
    public CommonResult<String> socialLogin(@RequestParam("type") Integer type,
                                            @RequestParam("redirectUri") String redirectUri) {
        return success(socialClientService.getAuthorizeUrl(
                type, UserTypeEnum.ADMIN.getValue(), redirectUri));
    }

    @PostMapping("/social-login")
    @PermitAll
    @Operation(summary = "社交快捷登录，使用 code 授权码", description = "适合未登录的用户，但是社交账号已绑定用户")
    public CommonResult<AuthLoginOutVO> socialQuickLogin(@RequestBody @Valid AuthSocialLoginInVO inVO) {
        return success(authService.socialLogin(inVO));
    }

}
